package database

import com.mongodb.MongoClient
import com.mongodb.client.model.Filters.eq
import org.bson.Document
import java.util.*


class MongoDbProperty(
    override var id: String,
    override var name: String,
    override var ip: String,
    override var port: Int,
    override var username: String,
    override var password: String
) : DataProperty() {
    override fun useProperty(): MutableMap<String, String> {
        return mutableMapOf()
    }
}

class MongoDbFactory(override val dataProperty: DataProperty) : DataMaster {
    private val dp = dataProperty.useProperty()

    val client = MongoClient("localhost", 27017)
    val database = client.getDatabase("local")

    init {
        connect()
    }

    fun connect(): Boolean {
        val dblist = client.listDatabases()

        return true
    }

    fun createCollection(name: String) {
        database.createCollection(name)
    }

    fun insertRecord() {
        val collection = database.getCollection("user")
        val doc = Document("name", "MongoDb")
            .append("type", "database")
            .append("count", 1)
            .append("info", Document("x", 203))
        collection.insertOne(doc)
    }

    fun insertMultiRecords() {
        val collection = database.getCollection("tutorals")
        val documents = mutableListOf<Document>()
        for(i in 0 until 5){
            documents.add(Document("i", Random().nextFloat()))
        }
        collection.insertMany(documents)
    }

    fun queryRecords() {
        val collection = database.getCollection("tutorals")
        val cursor = collection.find().iterator()
        while (cursor.hasNext()) {
            println(cursor.next().toJson())
        }
    }

    fun deleteRecord() {
        val collection = database.getCollection("tutorals")
        collection.deleteOne(eq("i", 0.249339759349823))
    }
}

fun main() {
    val dp = MongoDbProperty("mongoDb","本地 mongoDb 数据库", "127.0.0.1", 27017, "root", "root")
    val mongoDb = DataMaster.instance(dp) as MongoDbFactory //后面用抽象方法
//    mongoDb.createCollection("user")
//    mongoDb.insertRecord()
//    mongoDb.insertMultiRecords()
    mongoDb.queryRecords()
    mongoDb.deleteRecord()
    mongoDb.queryRecords()
}